<?php
namespace app\index\controller;
use think\Db;
use think\facade\View;
use think\Controller;
use think\Request;
use app\index\model\admin;
use app\index\Validate\admin as adminValidate;

class index extends Controller
{
    //数据列表
    public function index()
    {
        $keyword = input('keyword');
        $map = [];
        if($keyword) $map['username'] = ['like', '%' .$keyword. '%'];
        $list = admin::where($map)->order('id desc')->paginate(5);
        $page = $list->render();
        $this->assign('page', $page);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //数据添加
    public function add()
    {
        if(request()->isPost()){
            $post = input('post.');
            $val = new adminValidate();
            if(!$val->check($post)){
                $this->error($val->getError());
                die;
            }
            $data = [
                'username' => $post['username'],
                'password' => md5($post['password']),
                'email' => $post['email'],
                'create_time' => time()
            ];
            $res = admin::insert($data);
            if(!$res){
                $this->error('新增数据失败！');
            } else {
                $this->success('新增数据成功！', 'index');
            }
        }
        return $this->fetch();
    }

    //数据更新
    public function update()
    {
        if(request()->isPost()){
            $post = input('post.');
            $data = [
                'username' => $post['username'],
                'password' => md5($post['password']),
                'email' => $post['email'],
            ];
            $res = admin::where('id', $post['id'])->update($data);
            if(!$res){
                $this->error('数据更新失败！');
            } else {
                $this->success('数据更新成功！', 'index');
            }
        }
        $id = input('get.id');
        $info = admin::where('id',$id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    //数据删除
    public function delete()
    {
        $id = input('get.id');
        $res = admin::where('id',$id)->delete();
        if($res){
            return json(['msg' => '删除成功！','status' => 1]);
        }
        return $this->fetch();
    }

}

